﻿using Dapper;
using Entity;
using IRealize;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Realize;
using System.Data;
using System.Threading.Tasks;

namespace WebApplication9.Controllers.DDGL
{
    public class DDSHController : Controller
    {
        private readonly IConfiguration configuration;

        public DDSHController(IConfiguration configuration)
        {
            this.configuration = configuration;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult SHYM()
        {
            return View();
        }

        public async Task<IActionResult> DDXS(int pageSize, int currentPage)
        {

            string sqlserver = configuration["SqlServer"];
            using (SqlConnection conn = new SqlConnection(sqlserver))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@keyName", "mch_id");
                param.Add("@tableName", "major_change");
                param.Add("@currentPage", currentPage);
                param.Add("@totalRows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYedd] @pageSize, @keyName, @tableName, @currentPage, @totalRows out";
                List<Major_Change> list = conn.Query<Major_Change>(sql, param).ToList();

                FenYe<Major_Change> fenYecs = new FenYe<Major_Change>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("totalRows");
                //return fenYecs;
                return Json(fenYecs);

            }

        }



        public IActionResult Update(int id)
        {
            return View();
        }

        public async Task<IActionResult> Update1(int id)
        {
            IDDGLD dDGLD = new DDGLD();
            Major_Change fileDig = await dDGLD.SelectHuFiAsync(id, configuration["SqlServer"]);


            // 映射数据为前端需要的格式，包含原机构和原职位ID
            var result = new
            {
                success = true,
                data = new
                {

                    mch_id = fileDig.mch_id, //主键
                    human_id = fileDig.human_id,
                    human_name = fileDig.human_name,
                    // 原机构信息
                    original_first_kind_id = fileDig.first_kind_id,
                    original_first_kind_name = fileDig.first_kind_name,
                    original_second_kind_id = fileDig.second_kind_id,
                    original_second_kind_name = fileDig.second_kind_name,
                    original_third_kind_id = fileDig.third_kind_id,
                    original_third_kind_name = fileDig.third_kind_name,
                    // 原职位信息
                    original_job_category_id = fileDig.major_kind_id,
                    original_job_category_name = fileDig.major_kind_name,
                    original_job_id = fileDig.major_id,
                    original_job_name = fileDig.major_name,
                    // 原薪酬信息
                    original_salary_standard_name = fileDig.salary_standard_name,
                    original_salary_total = fileDig.salary_sum,


                    // 新机构信息
                    new_first_kind_id = fileDig.new_first_kind_id,
                    new_first_kind_name = fileDig.new_first_kind_name,
                    new_second_kind_id = fileDig.new_second_kind_id,
                    new_second_kind_name = fileDig.new_second_kind_name,
                    new_third_kind_id = fileDig.new_third_kind_id,
                    new_third_kind_name = fileDig.new_third_kind_name,

                    // 新职位信息
                    new_job_category_id = fileDig.new_major_kind_id,
                    new_job_category_name = fileDig.new_major_kind_name,
                    new_job_id = fileDig.new_major_id,
                    new_job_name = fileDig.new_major_name,

                    // 新薪酬信息
                    new_salary_standard_id = fileDig.new_salary_standard_id,
                    new_salary_standard_name = fileDig.new_salary_standard_name,
                    new_salary_total = fileDig.new_salary_sum,

                    // 其他原有字段...
                    checkrName = HttpContext.Session.GetString("PName"),

                     // 其他信息
                    registrant = fileDig.register,
                    change_reason = fileDig.change_reason, //调动原因

                    check_reason = fileDig.check_reason,//通过意见

                    checkr = fileDig.checker,
                    registration_time = fileDig.regist_time,

                }
            };

            return Ok(result);

        }






        public async Task<IActionResult> Approval([FromBody] Major_Change mc)
        {
            IDDGLD dDGLD = new DDGLD();

            HttpContext.Session.GetString("PName");

            // 调用AddHF方法
            int result = await dDGLD.UpdateMCTG(mc, configuration["SqlServer"]);

            if (result > 0)
            {
                return Ok(new { success = true, message = "修改成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "修改失败" });
            }

        }

        public IActionResult CGZS()
        {
            return View();
        }

        public IActionResult BTZS()
        {
            return View();
        }


        public async Task<IActionResult> Rejection([FromBody] Major_Change mc)
        {
            IDDGLD dDGLD = new DDGLD();


            // 调用AddHF方法
            int result = await dDGLD.UpdateMCBTG(mc, configuration["SqlServer"]);

            if (result > 0)
            {
                return Ok(new { success = true, message = "修改成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "修改失败" });
            }

        }






        [HttpGet("FirstLevelnewCXCG")]
        public async Task<IActionResult> FirstLevelnewCXCG()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 1. 查询I级机构
                var firstLevelOrgs = await connection.QueryAsync<dynamic>(
                    @"SELECT DISTINCT 
                first_kind_id AS id, 
                first_kind_name AS name 
              FROM human_file_dig 
              WHERE first_kind_id IS NOT NULL 
                AND first_kind_name IS NOT NULL");

                // 2. 查询II级机构
                var secondLevelOrgs = await connection.QueryAsync<dynamic>(
                    @"SELECT DISTINCT 
                second_kind_id AS id, 
                second_kind_name AS name,
                first_kind_id AS parentId  -- 关联I级机构的外键
              FROM human_file_dig 
              WHERE second_kind_id IS NOT NULL 
                AND second_kind_name IS NOT NULL");

                // 3. 查询III级机构
                var thirdLevelOrgs = await connection.QueryAsync<dynamic>(
                    @"SELECT DISTINCT 
                third_kind_id AS id, 
                third_kind_name AS name,
                second_kind_id AS parentId  -- 关联II级机构的外键
              FROM human_file_dig 
              WHERE third_kind_id IS NOT NULL 
                AND third_kind_name IS NOT NULL");

                // 构建正确的级联结构：I级 → II级 → III级
                var result = firstLevelOrgs.Select(first => new
                {
                    id = first.id,
                    name = first.name,
                    // 关联当前I级机构下的II级机构
                    children = secondLevelOrgs
                        .Where(second => second.parentId == first.id)
                        .Select(second => new
                        {
                            id = second.id,
                            name = second.name,
                            // 关联当前II级机构下的III级机构
                            children = thirdLevelOrgs
                                .Where(third => third.parentId == second.id)
                                .Select(third => new
                                {
                                    id = third.id,
                                    name = third.name
                                })
                                .ToList()
                        })
                        .ToList()
                }).ToList();

                return Ok(result);
            }
        }





    }
}
